<template>
  <div class="product-detail">
    <div v-if="tea">
      <h2>{{ tea.name }}</h2>
      <img :src="tea.imageUrl" alt="商品图片" style="max-width:300px;" />
      <p>类型：{{ tea.teaType?.name }}</p>
      <p>产地：{{ tea.origin }}</p>
      <p>价格：￥{{ tea.price }}</p>
      <p>库存：{{ tea.stock }}</p>
      <p>{{ tea.description }}</p>
      <h3>评论区</h3>
      <div v-if="reviews.length">
        <div v-for="r in reviews" :key="r.id" class="review-card">
          <b>{{ r.user?.username || '匿名' }}</b>：{{ r.comment }} <span style="color:#f90">{{ r.rating }}分</span>
        </div>
      </div>
      <div v-else>暂无评论</div>
      <div class="add-review">
        <h4>我要评论</h4>
        <textarea v-model="newComment" placeholder="请输入评论内容"></textarea>
        <select v-model="newRating">
          <option v-for="n in 5" :key="n" :value="n">{{ n }}分</option>
        </select>
        <button @click="submitReview">提交评论</button>
      </div>
    </div>
    <div v-else>加载中...</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();
const tea = ref<any>(null);
const reviews = ref<any[]>([]);
const newComment = ref('');
const newRating = ref(5);

const fetchTea = async () => {
  const { data } = await axios.get(`/api/Product/${route.params.id}`);
  tea.value = data;
};
const fetchReviews = async () => {
  const { data } = await axios.get(`/api/Product/${route.params.id}/reviews`);
  reviews.value = data;
};
const submitReview = async () => {
  if (!newComment.value) return alert('请输入评论内容');
  await axios.post(`/api/Product/${route.params.id}/reviews`, {
    comment: newComment.value,
    rating: newRating.value,
    userId: localStorage.getItem('userId') // 假设已登录
  });
  newComment.value = '';
  newRating.value = 5;
  fetchReviews();
};
onMounted(() => {
  fetchTea();
  fetchReviews();
});
</script>

<style scoped>
.product-detail { max-width: 600px; margin: 0 auto; }
.review-card { background: #f8f8f8; margin: 8px 0; padding: 8px; border-radius: 4px; }
.add-review { margin-top: 16px; }
textarea { width: 100%; min-height: 60px; margin-bottom: 8px; }
select { margin-right: 8px; }
button { background: #ff5000; color: #fff; border: none; padding: 6px 16px; border-radius: 4px; cursor: pointer; }
</style>
